import threading
import time
import serial

# Configure UART parameters
SERIAL_PORT = '/dev/ttyUSB0'  # Update this to your serial port
BAUD_RATE = 115200

# Initialize serial port
ser = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1)
ser.dtr = True  # Ensure DTR is set

def uart_receive():
    while True:
        if ser.in_waiting > 0:
            data = ser.readline().decode('utf-8').strip()
            if data:
                print(f"Received: {data}")
        time.sleep(0.01)

def periodic_send():
    while True:
        send_data = "Periodic Data\n"
        ser.write(send_data.encode('utf-8'))
        time.sleep(0.1)

if __name__ == "__main__":
    # Create threads for UART receive and periodic send
    receive_thread = threading.Thread(target=uart_receive, daemon=True)
    send_thread = threading.Thread(target=periodic_send, daemon=True)
    
    # Start threads
    receive_thread.start()
    send_thread.start()
    
    # Keep the main thread alive
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\nTerminating...")
        ser.close()
